<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Utils\ModelOperatorTrait;
use Illuminate\Validation\Rule;

class RoleController extends Controller
{
    use ModelOperatorTrait;

    protected function model(){
        return app(\App\Models\Role::class);
    }

    protected function getAttributes(){
        return [
            'name' => '角色名称',
            'permissionIds' => '权限组',
            'permissionIds.*' => '权限编号'
        ];
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return formatJsonResponse($this->pageModel(request()->input()));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|unique:roles,name',
            'permissionIds' => 'required|array',
            'permissionIds.*' => 'required|exists:permissions,id'
        ];

        $this->validate($rules);

        try {
            \DB::beginTransaction();

            $role = $this->storeModel($request->all());

            foreach ($request->permissionIds as $permissionId) {
                $this->storeModel(['role_id' => $role->id,'permission_id'=>$permissionId],app(\App\Models\RolePermission::class));
            }

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback();

            throw new \Exception($e->getMessage(),10003);
        }

        return formatJsonResponse();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return formatJsonResponse($this->findModel($id,['permissions']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $rules = [
            'name' => [
                'required',
                Rule::unique('roles','name')->where(function ($query) use ($id){
                    $query->where('id','<>', $id);
                })
            ],
            'permissionIds' => 'required|array',
            'permissionIds.*' => 'required|exists:permissions,id'
        ];

        $this->validate($rules);

        try {
            \DB::beginTransaction();

            $role = $this->updateModel($id,$request->all());

            $this->dropModel(['role_id' => $id],app(\App\Models\RolePermission::class));

            foreach ($request->permissionIds as $permissionId) {
                $this->storeModel(['role_id' => $id,'permission_id'=>$permissionId],app(\App\Models\RolePermission::class));
            }

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback();

            throw new \Exception($e->getMessage(),10003);
        }

        return formatJsonResponse();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            \DB::beginTransaction();

            $this->dropModel(['role_id' => $id],app(\App\Models\RolePermission::class));

            $this->deleteModel($id);

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback();

            throw new \Exception($e->getMessage(),10003);
        }
        return formatJsonResponse();
    }
}
